import React, { useState, useEffect, useCallback, useRef } from 'react';
import Search from 'antd/lib/input/Search';
import { Space, Button, Table, message, Modal } from 'antd';

import { ColumnsType } from 'antd/lib/table';
import { getSmsTempList, deleteSmsTemp, mulDelSmsTemp } from 'admin/servers/servers'; // http接口请求文件
import { SmsTempInfo } from 'admin/schema/SmsTemplate'; //
import { checkPermission } from 'permission/Index';
import SmsPop from './components/SmsPop';
import SmsDetail from './components/SmsDetail';
import moment from 'moment';
import { deleteRowChangePageNum } from 'utils/tools';

/**
 * 短信模板列表
 */
const SmsTempList: React.FC = () => {
  /**
   * 新增、编辑弹窗-ref
   */
  const childRef = useRef();
  // Table loading状态
  const [tableLoading, setTableLoading] = useState<boolean>(false);
  // 当前页码
  const [current, setCurrent] = useState<number>(1);
  // 每页条数
  const [pageSize, setPageSize] = useState<number>(10);
  // 数据总数
  const [total, setTotal] = useState<number>(0);
  // 搜索内容
  const [searchText, setSearchText] = useState<string>('');
  // 批量删除选择项
  const [selectedIds, setSelectedIds] = useState<number[]>([]);
  // table列表数据
  const [smsTemp, setSmsTempList] = useState<SmsTempInfo[]>([]);
  const [detailVisible, setDetailVisible] = useState<boolean>(false);
  const [detailForm, setDetailForm] = useState<SmsTempInfo>({
    templateId: 0,
    templateName: '',
    content: '',
    createTime: '',
  });

  /**
   * 查询table数据
   */
  const initData = useCallback(async () => {
    setTableLoading(true);
    try {
      const res = await getSmsTempList({
        pageNo: current,
        pageSize: pageSize,
        templateName: searchText,
      });
      const { data, count } = res;
      setSmsTempList(data || []);
      setTotal(Number(count) || 0);
    } catch (error) {
      console.error(`系统异常: ${JSON.stringify(error)}`);
    }
    setTableLoading(false);
  }, [current, pageSize, searchText]);

  useEffect(() => {
    initData();
  }, [initData]);

  /**
   * 搜索短信模板
   * @param text 搜索内容
   */
  const handleSearch = (text: string) => {
    text = text.trim();
    setSearchText(text);
    setCurrent(1);
  };

  /**
   * 新增短信模板
   */
  const handleAdd = () => {
    (childRef.current as any).open({}, () => {
      // 回调函数：操作成功，刷新列表
      refreshTable(1);
    });
  };

  /**
   * 编辑短信模板
   * @param text 搜索内容
   */
  const handleEdit = (obj: SmsTempInfo) => {
    (childRef.current as any).open(obj, () => {
      // 回调函数：操作成功，刷新列表
      refreshTable();
    });
  };

  /**
   * 查看详情-短信模板
   */
  const handleDetail = (obj: SmsTempInfo) => {
    setDetailVisible(true);
    setDetailForm(obj);
  };

  /**
   * 对table数据进行刷新：新增，编辑
   * @param pageNum 刷新页码
   */
  const refreshTable = async (pageNum?: number) => {
    if (pageNum) {
      current === pageNum ? initData() : setCurrent(pageNum);
    } else {
      initData();
    }
  };

  /**
   * 对table数据进行刷新：删除
   */
  function deleteFresh(size: number) {
    const newPageNum = deleteRowChangePageNum(size, total, current, pageSize);
    refreshTable(newPageNum);
  }

  /**
   * 删除短信模板
   */
  const handleDelete = (obj: SmsTempInfo) => {
    Modal.confirm({
      title: '删除模板提示',
      content: '删除后无法恢复! 确认删除吗?',
      onOk: () => {
        deleteSmsTemp(obj.templateId)
          .then(res => {
            message.success('删除成功');
            deleteFresh(1);
          })
          .catch(error => {
            console.error(`系统异常: ${JSON.stringify(error)}`);
          });
      },
    });
  };
  /**
   * 批量删除
   */
  const batchDelete = (): void => {
    const len = selectedIds.length;
    if (len === 0) {
      message.warn('请先选择项');
      return;
    }
    Modal.confirm({
      content: '删除后无法恢复，确认删除吗',
      onOk: () => {
        mulDelSmsTemp(selectedIds)
          .then(res => {
            message.success('删除成功');
            deleteFresh(len);
          })
          .catch(error => {
            console.error(`系统异常: ${JSON.stringify(error)}`);
          });
      },
    });
  };
  /**
   * Table列描述数据对象
   */

  const columns: ColumnsType<SmsTempInfo> = [
    {
      title: '序号',
      render: (text, record, index) => index + 1 + pageSize * (current - 1),
      width: 100,
    },
    {
      title: '模板名称',
      dataIndex: 'templateName',
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      render: (text, record, index) => {
        return moment(Number(text)).format('YYYY-MM-DD HH:mm');
      },
    },
    {
      title: '操作',
      dataIndex: 'operation',
      width: 240,
      render: (text, record, index) => (
        <Space size="small">
          {checkPermission('/smsManage/smsTemplate/modify') && (
            <Button type="link" onClick={() => handleEdit(record)}>
              编辑
            </Button>
          )}
          <Button type="link" onClick={() => handleDetail(record)}>
            详情
          </Button>
          {checkPermission('/smsManage/smsTemplate/delete') && (
            <Button type="link" onClick={() => handleDelete(record)}>
              删除
            </Button>
          )}
        </Space>
      ),
    },
  ];
  const rowSelection = {
    onChange: (selectedRowKeys: any, selectedRows: any) => {
      const selectedIds: number[] = [];
      selectedRows.forEach((item: any) => {
        selectedIds.push(item.templateId);
      });
      setSelectedIds(selectedIds);
    },
  };

  return (
    <>
      <div className="mgr-header">
        <div className="mgr-header-left">
          <Search
            placeholder="请输入模板名称"
            enterButton="搜索"
            style={{ width: 300 }}
            onSearch={value => handleSearch(value.trim())}
          />
        </div>
        <div className="mgr-header-right">
          {checkPermission('/smsManage/smsTemplate/add') && (
            <Button type="primary" onClick={() => handleAdd()}>
              新建模板
            </Button> // // todo：批量选择，批量删除
          )}
          {checkPermission('/smsManage/smsTemplate/delete') && (
            <Button onClick={batchDelete}>批量删除</Button>
          )}
        </div>
      </div>
      <div className="mgr-table">
        <Table
          rowSelection={{ type: 'checkbox', ...rowSelection }}
          loading={tableLoading}
          columns={columns}
          dataSource={smsTemp}
          rowKey="templateId"
          pagination={{
            current: current,
            total: total,
            pageSize: pageSize,
            showSizeChanger: true,
            // 改条数/页
            onShowSizeChange: (current, size) => {
              setPageSize(size);
            },
            // 改页码
            onChange: current => {
              setCurrent(current);
            },
            showTotal: total => `共${total}条`,
          }}
        />
      </div>
      <SmsPop cRef={childRef}></SmsPop>
      <SmsDetail
        visible={detailVisible}
        form={detailForm}
        onClose={() => {
          setDetailVisible(false);
        }}
      ></SmsDetail>
    </>
  );
};

export default SmsTempList;
